package co.yixiang.modules.auction.rest;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.modules.auction.domain.YxAuctionRecord;
import co.yixiang.modules.auction.domain.YxTerracePayInfo;
import co.yixiang.modules.auction.service.YxAuctionRecordService;
import co.yixiang.modules.auction.service.YxTerracePayInfoService;
import co.yixiang.modules.auction.service.dto.YxAuctionConfigDto;
import co.yixiang.modules.auction.service.dto.YxAuctionRecordDto;
import co.yixiang.modules.commom.domain.YxAppdict;
import co.yixiang.modules.commom.service.YxAppdictService;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBank;
import co.yixiang.modules.user.domain.YxUserinfo;
import co.yixiang.modules.user.service.YxUserBankService;
import co.yixiang.modules.user.service.YxUserinfoService;
import co.yixiang.modules.user.service.dto.YxUserBankDto;
import co.yixiang.utils.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@Api(value = "抢拍商品", tags = "抢拍:抢拍商品", description = "抢拍商品")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class YxAuctionRecordController {

        private final YxAuctionRecordService yxAuctionRecordService;
        private final YxUserinfoService yxUserinfoService;
        private final YxAppdictService yxAppdictService;
        private final YxUserBankService yxUserBankService;
        private final YxTerracePayInfoService terracePayInfoService;
        private final RedisUtils redisUtil;

    /**
     *首页查询活动专区
     */
    @GetMapping("/productRecord/example")
    @ApiOperation(value = "首页查询活动专区", notes = "首页查询活动专区")
    public ApiResult<List<YxAuctionConfigDto>> findProductExample(){
        return yxAuctionRecordService.findProductExample();
    }

    /**
     * 根据timeId查询抢拍商品列表
     */
    @GetMapping("/productRecord/list/{timeId}")
    @ApiOperation(value = "根据timeId查询抢拍商品列表", notes = "根据timeId查询抢拍商品列表")
    public ApiResult getYxAuctionProductPageList(@PathVariable String timeId,
                                                                              @RequestParam(value = "searchName",required = false)String searchName,
                                                                              @RequestParam(value = "page",defaultValue = "1") int page,
                                                                              @RequestParam(value = "limit",defaultValue = "10") int limit){
        if (StrUtil.isBlank(timeId) || !NumberUtil.isNumber(timeId)){
            throw new YshopException("参数错误");
        }
        Page<YxAuctionRecordDto> yxAuctionProductPageList=new Page<>();
        if((null ==searchName || "".equals(searchName)) && Long.valueOf(0)!= Long.valueOf(timeId)){
            Object o = redisUtil.get("time"+Long.valueOf(timeId)+"&page"+page);
            if(ObjectUtil.isEmpty(o)) return ApiResult.ok(yxAuctionProductPageList);
            JSONObject pList = JSONObject.parseObject(o.toString());
            pList.put("pages" , pList.getInteger("total")/30 + (pList.getInteger("total")%30 == 0 ? 0 : 1));
            return ApiResult.ok(pList);
        }
        return ApiResult.ok(yxAuctionRecordService.getYxAuctionProductPageList(page, limit,searchName, Long.valueOf(timeId)));
    }

    /**
     * 根据timeId查询抢拍商品列表
     */
    @GetMapping("/productRecord/getStartTime/{timeId}")
    @ApiOperation(value = "根据timeId获取开始时间", notes = "根据timeId获取开始时间")
    public ApiResult getStartTime(@PathVariable String timeId){
        if (StrUtil.isBlank(timeId) || !NumberUtil.isNumber(timeId)){
            throw new YshopException("参数错误");
        }
        return ApiResult.ok(yxAuctionRecordService.getStartTime(Long.valueOf(timeId)));
    }

    /**     * 根据type获取支付信息

     * @return
     */
    @PostMapping("/getAccountByType")
    @ApiOperation(value = "根据type获取支付信息",notes = "根据type获取支付信息")
    public ApiResult<Map<String,Object>> getAccountByType(@RequestParam("type")Integer type, @RequestParam("id")String id) {
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id) || 4 < type) {
            throw new YshopException("参数错误");
        }
        Map<String, Object> map = new HashMap<>();
        YxAuctionRecord yxAuctionRecord = yxAuctionRecordService.getById(Long.valueOf(id));
        if (null == yxAuctionRecord) {
            throw new YshopException("该抢拍商品不存在");
        }
        //管理员发布
        if (null == yxAuctionRecord.getUserId() || 0 == yxAuctionRecord.getUserId()) {
            //支付宝
            if (ObjectUtil.isNotEmpty(yxAuctionRecord.getPayId())){
                YxTerracePayInfo terracePayInfo = terracePayInfoService.getById(yxAuctionRecord.getPayId());
                if (1 == type) {
                    map.put("name", terracePayInfo.getZfbName());
                    map.put("account", terracePayInfo.getZfbNum());
                    map.put("code", terracePayInfo.getZfbCode());
                    //微信
                } else if (2 == type){
                    map.put("name", terracePayInfo.getWxName());
                    map.put("account", terracePayInfo.getWxNum());
                    map.put("code", terracePayInfo.getWxCode());
                }  else if (4 == type) {
                    map.put("name", terracePayInfo.getYhzsxm());
                    map.put("account", terracePayInfo.getYhkh());
                    map.put("code", terracePayInfo.getYhtp());
                    map.put("bankName", terracePayInfo.getYhkhh());
                }
            }else {
                if (1 == type) {
                    map.put("name", yxAppdictService.findAppdictByCode("zfbm").getMemo());
                    map.put("account", yxAppdictService.findAppdictByCode("zfbzh").getMemo());
                    map.put("code", yxAppdictService.findAppdictByCode("zfbcode").getImages());
                    //微信
                } else if (2 == type){
                    map.put("name", yxAppdictService.findAppdictByCode("wxm").getMemo());
                    map.put("account", yxAppdictService.findAppdictByCode("wxzh").getMemo());
                    map.put("code", yxAppdictService.findAppdictByCode("wxcode").getImages());
                }  else if (4 == type) {
                    map.put("name", yxAppdictService.findAppdictByCode("yhzsxm").getMemo());
                    map.put("account", yxAppdictService.findAppdictByCode("yhkh").getMemo());
                    map.put("code", yxAppdictService.findAppdictByCode("yhtp").getImages());
                    map.put("bankName", yxAppdictService.findAppdictByCode("yhkhh").getMemo());
                }
            }
        }else{
            YxUserinfo yxUserinfo =yxUserinfoService.selectByUserId(Long.valueOf(yxAuctionRecord.getUserId()));
            //支付宝
            if (1 == type) {
                map.put("name", yxUserinfo.getZhifubaoName());
                map.put("account", yxUserinfo.getZhifubaoAccount());
                map.put("code", yxUserinfo.getZhifubaoCode());
                //微信
            } else if (2 == type){
                map.put("name", yxUserinfo.getWeixinName());
                map.put("account",yxUserinfo.getWeixinAccount());
                map.put("code",yxUserinfo.getWeixinCode());
            }  else if (4 == type) {
                List<YxUserBank> yxUserBanks=yxUserBankService.selectAllByUserId(yxAuctionRecord.getUserId());
                if(yxUserBanks.size()>0){
                    map.put("name", yxUserBanks.get(0).getRealName());
                    map.put("account", yxUserBanks.get(0).getBankNumber());
                    map.put("code", yxUserBanks.get(0).getImage());
                    map.put("bankName", yxUserBanks.get(0).getBankName());
                }else{
                    map.put("name", "");
                    map.put("account", "暂无账号");
                    map.put("code", "暂无收款码");
                    map.put("bankName", "暂无");
                }
            }
        }
        return ApiResult.ok(map);
    }

    /**
     * 抢拍商品详情
     */
    @AuthCheck
    @GetMapping("/productRecord/detail/{id}")
    @ApiOperation(value = "抢拍商品详情", notes = "抢拍商品详情")
    public ApiResult<YxAuctionRecordDto> getYxAuctionProductDetail(@PathVariable String id){
        YxUser yxUser = LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        return ApiResult.ok(yxAuctionRecordService.getYxAuctionProductDetail(yxUser.getUid(),Long.valueOf(id)));
    }

    /**
     * 我的卖单列表
     * 1等待转拍2转拍中3待确定4转拍完成
     */
    @AuthCheck
    @GetMapping("/productRecord/orderPage/{type}")
    @ApiOperation(value = "我的卖单列表", notes = "我的卖单列表")
    public ApiResult<Page<YxAuctionRecordDto>> orderPage(@PathVariable String type ,
                                                   @RequestParam(value = "page",defaultValue = "1") int page,
                                                     @RequestParam(value = "limit",defaultValue = "10") int limit){
        YxUser yxUser = LocalUser.getUser();
        if (StrUtil.isBlank(type) || !NumberUtil.isNumber(type)){
            throw new YshopException("参数错误");
        }
        return ApiResult.ok(yxAuctionRecordService.orderPage(yxUser.getUid(),Integer.valueOf(type),page,limit));
    }


    /**
     * 我的卖单详情
     *id为我的卖单id
     */
    @AuthCheck
    @GetMapping("/productRecord/productReocrdDetail/{id}")
    @ApiOperation(value = "我的卖单详情", notes = "我的卖单详情")
    public ApiResult<YxAuctionRecordDto> productReocrdDetail(@PathVariable String id ){
        YxUser yxUser = LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        return ApiResult.ok(yxAuctionRecordService.productReocrdDetail(yxUser.getUid(),Long.valueOf(id)));
    }

  /*  *
     * 确认收款
     *id为我的卖单id
     */
    @AuthCheck
    @GetMapping("/productRecord/confirmPay/{id}")
    @ApiOperation(value = "确认收款", notes = "确认收款")
    public ApiResult<Object> confirmPay(@PathVariable String id ){
        YxUser yxUser = LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        return yxAuctionRecordService.confirmPay(yxUser.getUid(),Long.valueOf(id));
    }
}
